package com.macro.mall.tiny.component.tencent;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class CosComponent {

    private final COSClient cosClient;

    @Value("${tencent.cos.bucketName}")
    private String bucketName;

    public CosComponent(COSClient cosClient) {
        this.cosClient = cosClient;
    }

    // 上传文件到腾讯云 COS
    public String uploadFile(MultipartFile file, String path) throws IOException {
        // 创建一个临时文件
        File localFile = convertMultipartFileToFile(file);

        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path + file.getOriginalFilename(), localFile);

        // 上传文件
        cosClient.putObject(putObjectRequest);

        // 删除临时文件
        localFile.delete();

        // 返回文件的访问 URL
        return "https://cdn.weixiuzhushou.top/" + path + file.getOriginalFilename();
    }

    public String uploadMemberIcon(String url, String openId, String path) {
        try {
            File tempFile = downloadImageFromUrl(url, openId);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path + openId + ".jpg", tempFile);
            cosClient.putObject(putObjectRequest);
            String viewPath = "https://cdn.weixiuzhushou.top/" + path + openId + ".jpg";
            return viewPath;
        } catch (Exception e) {
            return null;
        }
    }

    // 将 MultipartFile 转换为 File 对象
    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private static File downloadImageFromUrl(String imageUrl, String openId) throws Exception {
        URL url = new URL(imageUrl);
        InputStream in = url.openStream();
        File tempFile = File.createTempFile(openId, ".jpg");

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            in.close();
        }

        return tempFile;
    }

    public COSClient getCosClient() {
        return cosClient;
    }


    public void downloadFile(String path, HttpServletResponse response) {
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
            COSObject object = cosClient.getObject(getObjectRequest);
            COSObjectInputStream objectContent = object.getObjectContent();
            String[] split = object.getKey().split("/");
            String fileName = split[split.length - 1];
            String encode = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encode + "\"");

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = objectContent.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            objectContent.close();
            response.getOutputStream().flush();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            log.error("下载文件失败", e);
        }


    }
}